/*
 * @Description:
 * @Version: 2.0
 * @Autor: zhangjx
 * @Date: 2023-05-23 11:06:39
 * @LastEditors: uphldjx 1373577124@qq.com
 * @LastEditTime: 2024-07-19 15:17:41
 */
// import { fileURLToPath, URL } from 'node:url'
import type { UserConfig, ConfigEnv } from 'vite'
import { loadEnv } from 'vite'
import fs from 'fs'
import path from 'path'
import { createVitePlugins } from './build/vite'
// https://vitejs.dev/config/
export default ({ command, mode }: ConfigEnv): UserConfig => {
	const env = loadEnv(mode, process.cwd())
	const optimizeDepsElementPlusIncludes = ['element-plus/es']
	fs.readdirSync('node_modules/element-plus/es/components').map((dirname) => {
		fs.access(`node_modules/element-plus/es/components/${dirname}/style/css.mjs`, (err) => {
			if (!err) {
				optimizeDepsElementPlusIncludes.push(`element-plus/es/components/${dirname}/style/css`)
			}
		})
	})

	return {
		plugins: createVitePlugins(mode),
		resolve: {
			extensions: ['.js', '.ts', '.tsx', '.jsx'],
			alias: {
				'@': path.resolve(__dirname, './src'),
				// '@': fileURLToPath(new URL('./src', import.meta.url)),
			},
		},
		base: './',
		optimizeDeps: {
			include: optimizeDepsElementPlusIncludes,
		},
		server: {
			host: '0.0.0.0',
			port: 8084,
			open: false,
			headers: {
				'Access-Control-Allow-Origin': '*',
			},
			hmr: {
				overlay: false,
			},
			warmup: {
				clientFiles: ['./src/components/*.vue', './src/utils/util.ts'],
			},
			proxy: {
				'/api': {
					target: env.VITE_PROXY_URL,
					changeOrigin: true,
					rewrite: (path) => path.replace(/^\/api/, ''),
				},
				'/export': {
					target: env.VITE_EXPORT_PROXY_URL,
					changeOrigin: true,
					rewrite: (path) => path.replace(/^\/export/, ''),
				},
			},
		},
		css: {
			preprocessorOptions: {
				scss: {
					additionalData: `@use "@/styles/scss/variables.scss" as *;`,
					charset: false,
				},
			},
		},
		esbuild: {
			drop: mode === 'development' ? [] : ['console', 'debugger'],
		},
		build: {
			manifest: true,
			chunkSizeWarningLimit: 1000,
			assetsInlineLimit: 4096,
			sourcemap: false,
			reportCompressedSize: false,
			rollupOptions: {
				output: {
					chunkFileNames: 'assets/js/[name]-[hash].js',
					entryFileNames: 'assets/js/[name]-[hash].js',
					assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
					experimentalMinChunkSize: 10 * 1024,
					manualChunks(id) {
						if (id.includes('node_modules')) {
							return id.toString().split('node_modules/')[1].split('/')[0].toString()
						}
					},
				},
			},
		},
	}
}
